//
//  CZOauthViewController.swift
//  XLWB009
//
//  Created by apple on 3/23/16.
//  Copyright © 2016 apple. All rights reserved.
//

import UIKit
import SVProgressHUD

class CZOauthViewController: UIViewController {
    
    override func loadView() {
        view=webView
        
        //代理
        webView.delegate=self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //设置背景颜色
       view.backgroundColor=UIColor.whiteColor()
        
        //设置导航栏
        setNavigationBar()
        
        //使用webView加载登陆界面
        let url=NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)")
//        print("-----",url)
        
        let request=NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
        //设置加载
        SVProgressHUD.showWithStatus("正在加载", maskType: SVProgressHUDMaskType.Black)
    }

    //设置导航栏按钮
    func setNavigationBar() {
        
        navigationItem.leftBarButtonItem=UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autofell")
        
        navigationItem.rightBarButtonItem=UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    //点击方法
    //填充
    @objc private func autofell(){
        //js代码字符串
        let jsCode="document.getElementById('userId').value='450037443@qq.com';document.getElementById('passwd').value='dengzhihua'"
        
        //执行js代码
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }
    
    //取消
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //定义懒加载webview
    private lazy var webView:UIWebView=UIWebView()
}

//扩展CZOauthViewController 实现CZVisitorViewDelegate
extension CZOauthViewController:UIWebViewDelegate{
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //关闭提示
        SVProgressHUD.dismiss()
    }
    
    //截取网页
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString=request.URL!.absoluteString
        print(urlString)
//        当点击了取消授权后都会加载授权回请地址，所以如果判断点击或者取消授权
//        不是授权回请地址，加载
        if !urlString.hasPrefix(redirect_uri) {
            return true
        } else {
            // 加载的授权回调地址,说明点击的是 取消 或 授权
            // 获取参数
            // query: get请求?后面的参数
            let query = request.URL?.query
            
            // 判断query是否以code=开头
            let codeString = "code="
            if query!.hasPrefix(codeString) {
                // 点击的是 授权
                // "code=b2e409e0c79fa29dd9a3dc903f18ca73"
                // 截取query里面的code
                let nsQuery = query! as NSString
                let code = nsQuery.substringFromIndex(codeString.characters.count)
                print("code: \(code)")
                
                /// 3.准备好闭包
                CZUserAccoutModel.sharedInstance.loadAccessToken(code, completion: { (error) -> () in
                    // 判断是否有错
                    if error != nil {
                        print("error: \(error)")
                        SVProgressHUD.showErrorWithStatus("获取AccessToken失败")
                        
                        // 延迟1秒再关闭
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.close()
                        })
                        return
                    }
                    
                    // 没有错误
                    // 关闭控制器
                    print("没有错误关闭控制器")
                    self.close()
                    // 切换控制器
                    AppDelegate.outswitchRootViewController(CZWelcomViewController())
//                   let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
//                    appDelegate?.window?.rootViewController=CZWelcomViewController()
                })
            } else {
                // 点击的是取消
                // 关闭界面
                close()
                
            }
            
            return false
        }
    }
    
    //关闭控制器
    func code() {
        
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true) {  }
    }
}